﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace svg2xaml
{
    class Program
    {
        public static int SuccessCount;
        public static int FailCount;

        [STAThread]
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("usage: svg2xaml [/r] SourceFileOrFolder");
                Console.WriteLine("/r Process all *.svg files in the folder recursively.");
                return;
            }

            if (args[0] == "/r")
            {
                var stopwatch = new Stopwatch();
                stopwatch.Start();
                foreach (string file in Directory.GetFiles(args[1], "*.svg", SearchOption.AllDirectories))
                {
                    var resultFile = ConvertXaml2Svg(file);
                    if (resultFile != null)
                        RenderPreview(resultFile, resultFile + ".png", 255, 255);                    
                }
                stopwatch.Stop();
                Console.WriteLine("{0} conversions completed.  {1} conversions failed.  Total Time: {2}ms", SuccessCount, FailCount, stopwatch.ElapsedMilliseconds);
            }
            else
            {
                var resultFile = ConvertXaml2Svg(args[0]);
                if (resultFile != null)
                    RenderPreview(resultFile, resultFile + ".png", 255, 255);
            }

            //Console.WriteLine("Press any key to continue.");
            //Console.ReadLine();
        }

        static System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();

        public static string ConvertXaml2Svg(string filename)
        {
            Console.WriteLine("{0}: Converting {1}", DateTime.Now, filename);
            string dest = Path.ChangeExtension(filename, ".xaml");

            try
            {
                stopwatch.Reset();
                stopwatch.Start();

                //using (var stream = File.Create(dest))
                //    XamlTune.ConvertUtility.ConvertSvg(filename, stream);

                using (var stream = File.Create(dest))
                    XamlWriter.Save(XamlTune.ConvertUtility.LoadSvg(filename), stream);

                //var result = XamlTune.ConvertUtility.ConvertFromSVG(File.ReadAllText(filename));
                //File.WriteAllText(dest, result);

                stopwatch.Stop();
                Console.WriteLine("{0}: Converted in {1}ms", DateTime.Now, stopwatch.ElapsedMilliseconds);
            }
            catch (Exception e)
            {
                FailCount++;
                Console.WriteLine(e.ToString());
                return null;
            }

            SuccessCount++;            
            return dest;
        }

        public static void RenderPreview(string filename, string outputFilename, double width, double height)
        {
            Console.WriteLine("{0}: Rendering preview.", DateTime.Now);
            try
            {
                using (FileStream stream = File.OpenRead(filename))
                {
                    FrameworkElement root = (FrameworkElement)XamlReader.Load(stream);

                    Viewbox box = new Viewbox();
                    box.Child = root;
                    box.HorizontalAlignment = HorizontalAlignment.Stretch;
                    box.VerticalAlignment = VerticalAlignment.Stretch;
                    root = box;

                    root.Measure(new Size(width, height));
                    root.Arrange(new Rect(new Size(width, height)));

                    RenderTargetBitmap bmp = new RenderTargetBitmap(Convert.ToInt32(width), Convert.ToInt32(height), 96, 96, PixelFormats.Pbgra32);
                    bmp.Render(root);

                    using (FileStream pngStream = new FileStream(outputFilename, FileMode.Create))
                    {
                        PngBitmapEncoder encoder = new PngBitmapEncoder();
                        encoder.Interlace = PngInterlaceOption.On;
                        encoder.Frames.Add(BitmapFrame.Create(bmp));
                        encoder.Save(pngStream);
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
                FailCount++;
            }
        }
    }
}
